<template>
  <div class="page-container-padding">
    <!-- 显示选择品种和创建数据表 -->
    <div style="display:flex;align-items: center;">
      <div class="flex-item">
      <el-select filterable size="mini" v-model="currentVariety.variety_en" placeholder="请选择品种" @change="getSheetWithVariety">
        <el-option v-for="item, index in varietyList" :label="item.variety_name+item.variety_en" :value="item.variety_en" :key="index"></el-option>
      </el-select>
      </div>
      <div style="display: flex;align-items: center;" v-show="currentVariety.variety_en">
        <div class="flex-item">
          <span>表名称:</span>
        </div>
        <div class="flex-item">
          <el-input size="mini" placeholder="输入新建表的名称" v-model.trim="newSheetName"></el-input>
        </div>
        <div class="flex-item">
          <el-button size="mini" type="primary" @click="toCreateSheet">
            确定新建
          </el-button>
        </div>
        <div class="flex-item">
          <el-button size="mini" type="text" icon="el-icon-document">
            <a :href="guidePdfUrl" target="_blank">操作指南</a>
          </el-button>
        </div>
      </div>
      <div style="margin-left: auto">
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-coin"
          @click="toShowMyIndexes"
        >
          我的指标库
        </el-button>
      </div>
    </div>
    <!-- 显示表和添加数据 -->
    <div style="display: flex; margin-top: 6px">
      <el-card style="width: 25%; min-height: calc(100vh - 116px)">
      <div style="background-color: #1890FF;color: #fff;padding: 0px 8px;height: 32px;line-height: 32px;">
        <span>数据表</span>
        <span style="color: #FFAE0D;">[{{ sheetList.length }}]</span>
        <span style="float: right;"><el-checkbox v-model="isShowOwn" @change="isOwnChange"><span style="color:#fff;">只看我的</span></el-checkbox></span>
      </div>
      <div v-if="sheetList.length<1" style="padding:8px;">
        <el-empty description="该品种没有数据表" v-loading="loadingVarietySheet"></el-empty>
      </div>
      <div v-else style="height:calc(100vh - 148px);overflow-y:scroll;">
        <div v-for="item,index in sheetList" :key="index">
          <div class="shee-name-node">
            <span class="sheet-name" @click="sheetRowClicked(item)">{{ item.name }}</span>
            <span class="list-action-btns">
              <el-button icon="el-icon-delete"
              size="mini"
              circle
              type="danger"
              @click="toDelSheet(item)"
              ></el-button>
            </span>
          </div>
        </div>
      </div>
      </el-card>
      <!-- 数据指标显示 -->
      <div style="width: 10px"></div>
      <el-card style="width: calc(75% - 10px); min-height: calc(100vh - 116px)">
        <div class="right-header">
          <div v-if="currentSheet.name">
            <span
              style="padding-right: 20px; font-size: 14px; font-weight: 700"
            >
              <i class="el-icon-s-opportunity"></i>
              {{ currentSheet.name }}
            </span>

            <el-button type="text" @click="showIndexForAdd = !showIndexForAdd">
              添加指标
            </el-button>

            <span v-show="multipleSelection.length>0">
              <el-divider direction="vertical"></el-divider>
              <el-button
                type="text"
                :loading="exportExcelLoading"
                @click="exportExcelFile"
              >
                导出EXCEL
              </el-button>
              <el-button type="text" @click="toShowIndexCalcultor">
                指标运算
              </el-button>
              <el-button
                type="text"
                :loading="sheetDataLoading"
                @click="sheetDataViewer"
              >
                查看数据
              </el-button>
              <el-button
                type="text"
                :loading="chartDataLoading"
                @click="toMakeCharts"
              >
                可视化制图
              </el-button>
            </span>
          </div>
        </div>

        <!-- 添加指标的操作 -->
        <el-collapse-transition>
          <div
            v-show="showIndexForAdd"
            v-loading="searchIndexLoading"
            style="margin: 5px 10px"
          >
            <div style="display: flex; align-items: center">
              <el-select
                v-model="searchSheetVariety"
                filterable
                size="mini"
                placeholder="全部品种"
                clearable
                style="margin-right: 10px; width: 140px"
                @change="toSearchIndexes"
              >
                <el-option
                  v-for="(v, i) in varietyList"
                  :key="i"
                  :value="v.variety_en"
                  :label="v.variety_name + v.variety_en"
                ></el-option>
              </el-select>
              <el-input
                v-model="searchSheetWords"
                clearable
                size="mini"
                placeholder="指标关键词搜索,指定品种时结果也含有无法分类到品种内的指标!"
                style="margin-right: 10px"
                @change="toSearchIndexes"
              ></el-input>
              <el-button
                icon="el-icon-search"
                size="mini"
                type="primary"
                @click="toSearchMyIndexes"
              >
                搜指标
              </el-button>
              <el-button
                icon="el-icon-search"
                size="mini"
                type="primary"
                @click="toSearchMyFormula"
              >
                搜公式
              </el-button>
            </div>
            <!-- 显示公式搜索结果 -->
            <el-table
              v-if="showFormulaTable"
              :data="queryFormulaList"
              height="300px"
            >
              <el-table-column show-overflow-tooltip label="操作" width="50px">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    @click="addFormulaToSheet(scope.row, scope.$index)"
                  >
                    添加
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="公式名称" min-width="300px">
                <template slot-scope="scope">
                  <span
                    class="table-index-name"
                    @dblclick="addFormulaToSheet(scope.row, scope.$index)"
                  >
                    {{ scope.row.name }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="formula"
                label="公式"
                width="420px"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                prop="frequency"
                label="频率"
                width="60px"
              ></el-table-column>
              <el-table-column
                prop="unit"
                label="单位"
                width="70px"
                show-overflow-tooltip
              ></el-table-column>
            </el-table>
            <!-- 显示指标搜索结果 -->
            <el-table v-else :data="querySheetList" height="300px">
              <el-table-column show-overflow-tooltip label="操作" width="50px">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    @click="addIndexToSheet(scope.row, scope.$index)"
                  >
                    添加
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column
                prop="name_zh"
                label="指标名称"
                min-width="300px"
              >
                <template slot-scope="scope">
                  <span
                    class="table-index-name"
                    @dblclick="addIndexToSheet(scope.row, scope.$index)"
                  >
                    {{ scope.row.name_zh }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="frequency"
                label="频率"
                width="60px"
              ></el-table-column>
              <el-table-column
                prop="source_plat"
                label="源"
                width="60px"
              ></el-table-column>
              <el-table-column
                prop="unit"
                label="单位"
                width="70px"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                prop="refresh"
                label="更新时间"
                width="136px"
              ></el-table-column>
            </el-table>
            <el-pagination
              small
              layout="total,prev,pager,next"
              :page-size="searchPageSize"
              :total="searchTotalCount"
              @current-change="searchIndexPageChange"
            ></el-pagination>
            <div style="float: left;position: relative;top: -18px;left: 50%;cursor: pointer;color: #1386d2;font-size: 12px;">
              <i class="el-icon-caret-top" @click="showIndexForAdd = false">
                收起
              </i>
            </div>
            <div style="float:right;position: relative;top: -18px;">
              当前搜索模式:
              <span style="font-weight: 700; color: #349cfc">
                {{ showFormulaTable ? '【公式】' : '【指标】' }}
              </span>
            </div>
          </div>
        </el-collapse-transition>
        <!-- 隔离带 -->
        <div
          v-show="showIndexForAdd"
          style="height: 20px; background-color: #f4f4f4"
        ></div>
        <!-- 数据指标显示表 -->
        <div>
          <div v-if="curSheetColumnList.length<1">
            <el-empty description="当前表还没添加数据指标"></el-empty>
          </div>
          <div v-else>
            <el-table ref="multipleTable" :data="curSheetColumnList" @selection-change="handleSelectionChange" :height="showIndexForAdd?'calc(100vh - 538px)':'calc(100vh - 148px)'">
              <el-table-column type="selection" width="45"></el-table-column>
              <el-table-column show-overflow-tooltip label="指标名称" prop="name" min-width="320px">
                <template slot-scope="scope">
                  <span class="table-index-name" @dblclick="delIndexWithSheet(scope.row)">{{ scope.row.name}}</span>
                </template>
              </el-table-column>
              <el-table-column show-overflow-tooltip label="公式" prop="formula" min-width="150px"></el-table-column>
              <el-table-column show-overflow-tooltip label="频率" prop="frequency" min-width="60"></el-table-column>
              <el-table-column show-overflow-tooltip label="单位" prop="unit" width="70px"></el-table-column>
              <el-table-column width="60px" label="操作">
                <template slot-scope="scope"><el-button type="text" @click="toAddOnBasis(scope.row)">添加环比</el-button></template>
              </el-table-column>
              <el-table-column show-overflow-tooltip width="60px">
                <template #default="{ row }">
                  <el-button type="text" @click='delIndexWithSheet(row)' style="color:#FF0000">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 数据制图的弹窗 -->
    <el-dialog :show-close="false" :fullscreen="chartDialogFullScreen" :visible.sync="showMakeChartDialog" width="82%" top="2%" @closed="makeChartDialogClosed">
      <div slot="title" style="display: flex; align-items: center;">
        <span>数据可视化</span>
        <div style="margin-left: auto;">
          <i v-if="chartDialogFullScreen" class="el-icon-crop" @click="chartDialogFullScreen=false"></i>
          <i v-else class="el-icon-full-screen" @click="chartDialogFullScreen=true"></i>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <i class="el-icon-close" @click="showMakeChartDialog=false"></i>
        </div>
      </div>
      <el-row :gutter="2">
        <!-- 左侧设置图形参数 -->
        <el-col :span="5">
          <el-card>
            <div
              style="padding-left: 5px;background-color: #ff7e1c;line-height: 24px;">
              图形指标
            </div>
            <div style="overflow: auto; margin: 2px 5px">
              <div v-for="item in chartSeriesIndex" :key="item.id">
                <el-checkbox
                  slot="reference"
                  v-model="item.isChecked"
                  @change="drawTargetChartUp"
                >
                  <!-- <span :title="item.name">{{ item.name }}</span> -->
                  <el-tooltip class="item" effect="dark" :content="item.name" placement="top-start">
                    <span>{{ item.name }}</span>
                  </el-tooltip>
                </el-checkbox>
              <div style="margin-left:50px;">
                <el-checkbox slot="reference" v-model="item.noZero" @change="drawTargetChartUp"><span>制图时去掉数据0</span></el-checkbox>
              </div>
              <div style="margin-left: 24px;">
                <el-radio :disabled="!item.isChecked" v-model="item.yIndex" :label="0" @change="drawTargetChartUp">左轴</el-radio><el-radio :disabled="!item.isChecked" v-model="item.yIndex" :label="1" @change="drawTargetChartUp">右轴</el-radio>
                <el-radio :disabled="!item.isChecked" v-model="item.chartType" label="line" @change="drawTargetChartUp">线形</el-radio><el-radio :disabled="!item.isChecked" v-model="item.chartType" label="bar" @change="drawTargetChartUp">柱状</el-radio>
              </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <!-- 中间显示图形 -->
        <el-col :span="13">
          <el-card>
            <div style="height: 350px;margin: 5px 8px;position: relative;">
              <vab-chart ref="popChart" autoresize theme="vab-echarts-theme" :option="popupChartOption"></vab-chart>
              <div style="font-size: 20px;color:rgba(0,0,0,0.2);" v-show="chartWartermark">
                <div style="position:absolute;top:100px;left:80px;">{{ chartWartermark }}</div>
                <div style="position:absolute;top:220px;right:80px">{{ chartWartermark }}</div>
              </div>
            </div>
          </el-card>
          <div style="margin-top:5px;">
            <div style="display: flex;align-items: center;">
              <div><el-checkbox v-model="isSeasonChart" @change="drawTargetChartUp">季节图形</el-checkbox></div>
              <div style="margin-left: auto;"><el-button type="primary"  @click="confirmSaveChartOption" :loading="saveChartLoading">保存</el-button></div>
            </div>
            <div style="color:#FF430D;margin-top:6px;">
              提示：如果指标为公式运算出来的，作图时选择去0，则图形不会立刻改变为去0的结果，可保存后查看最终图形。
            </div>
          </div>
        </el-col>
        <!-- 右侧设置图形其他参数 -->
        <el-col :span="6">
          <el-card>
            <div style="padding-left:5px;background-color: #62c8ff;line-height: 24px;">参数设置</div>
            <div style="padding: 5px 8px;overflow: auto;width: 250px;">
              <el-row :gutter="1" type="flex" align="middle">
                <el-col :span="8">标题</el-col>
                <el-col :span="16"><el-input type="text" v-model="popupChartOption.title.text" size="mini" placeholder="填写图形的名称"></el-input></el-col>
              </el-row>
              <br>
              <el-row :gutter="1" type="flex" align="middle">
                <el-col :span="8">横轴格式</el-col>
                <el-col :span="16">
                  <el-select v-model="xAxisFormate" @change="xAxisFomateChange" size="mini">
                    <el-option value="%Y-%m-%d" label="日"></el-option>
                    <el-option value="%Y-%m" label="月"></el-option>
                    <el-option value="%Y" label="年"></el-option>
                  </el-select>
                </el-col>
              </el-row>
              <br>
              <el-row :gutter="1" type="flex" align="middle">
                <el-col :span="8">横轴旋转<el-tooltip content="横坐标的旋转角度(-90~90)"><i class="el-icon-question"></i></el-tooltip></el-col>
                <el-col :span="16"><el-input-number v-model="popupChartOption.xAxis[0].axisLabel.rotate" size="mini" :min="-90" :max="90"></el-input-number></el-col>
              </el-row>
              <br>
              <el-row :gutter="1" type="flex" align="middle">
                <el-col :span="8">最大刻度<el-tooltip content="是否显示横轴最大刻度"><i class="el-icon-question"></i></el-tooltip></el-col>
                <el-col :span="16"><el-checkbox v-model="showChartMaxLabel" @change="chartMaxLabelShowChange">显示</el-checkbox></el-col>
              </el-row>
              <br>
              <el-row :gutter="1" type="flex" align="middle">
                <el-col :span="8">起始日期<el-tooltip content="横轴数据开始日期,不填则随数据变化."><i class="el-icon-question"></i></el-tooltip></el-col>
                <el-col :span="16"><el-date-picker clearable v-model="xAxisStartDate" size="mini" :default-value="cacheXaxisData[0]" style="width: 167px;"></el-date-picker></el-col>
              </el-row>
              <br>
              <el-row :gutter="1" type="flex" align="middle">
                <el-col :span="8">结束日期<el-tooltip content="横轴数据结束日期,不填则随数据变化."><i class="el-icon-question"></i></el-tooltip></el-col>
                <el-col :span="16"><el-date-picker clearabl v-model="xAxisEndDate" size="mini" :default-value="cacheXaxisData.slice(-1)" style="width: 167px;"></el-date-picker></el-col>
              </el-row>
              <br>
              <el-row :gutter="1" type="flex" align="middle">
                <el-col :span="8">左边距离<el-tooltip content="组件距离左边像素"><i class="el-icon-question"></i></el-tooltip></el-col>
                <el-col :span="16"><el-input-number v-model="popupChartOption.grid.left" size="mini"></el-input-number></el-col>
              </el-row>
              <br>
              <el-row :gutter="1" type="flex" align="middle">
                <el-col :span="8">上边距离<el-tooltip content="组件距离上边像素"><i class="el-icon-question"></i></el-tooltip></el-col>
                <el-col :span="16"><el-input-number v-model="popupChartOption.grid.top" size="mini"></el-input-number></el-col>
              </el-row>
              <br>
              <el-row :gutter="1" type="flex" align="middle">
                <el-col :span="8">右边距离<el-tooltip content="组件距离右边像素"><i class="el-icon-question"></i></el-tooltip></el-col>
                <el-col :span="16"><el-input-number v-model="popupChartOption.grid.right" size="mini"></el-input-number></el-col>
              </el-row>
              <br>
              <el-row :gutter="1" type="flex" align="middle">
                <el-col :span="8">下边距离<el-tooltip content="组件距离下边像素(建议: 图例行数 * 21)"><i class="el-icon-question"></i></el-tooltip></el-col>
                <el-col :span="16"><el-input-number v-model="popupChartOption.grid.bottom" size="mini"></el-input-number></el-col>
              </el-row>
              <br>
              <el-row :gutter="1" type="flex" align="middle">
                <el-col :span="8">左轴最小<el-tooltip content="可设置`dataMin`字样表示自动取最小值"><i class="el-icon-question"></i></el-tooltip></el-col>
                <el-col :span="16"><el-input clearable v-model="popupChartOption.yAxis[0].min" type="text" placeholder="左轴最小值" size="mini"></el-input></el-col>
              </el-row>
              <br>
              <el-row :gutter="1" type="flex" align="middle">
                <el-col :span="8">左轴最大<el-tooltip content="可设置`dataMax`字样表示自动取最大值"><i class="el-icon-question"></i></el-tooltip></el-col>
                <el-col :span="16"><el-input clearable v-model="popupChartOption.yAxis[0].max" type="text" placeholder="左轴最大值" size="mini"></el-input></el-col>
              </el-row>
              <br>
              <span v-show="popupChartOption.yAxis[1].show">
              <el-row :gutter="1" type="flex" align="middle">
                <el-col :span="8">右轴最小<el-tooltip content="可设置`dataMin`字样表示自动取最小值"><i class="el-icon-question"></i></el-tooltip></el-col>
                <el-col :span="16"><el-input clearable v-model="popupChartOption.yAxis[1].min" type="text" placeholder="右轴最小值" size="mini"></el-input></el-col>
              </el-row>
              <br>
              <el-row :gutter="1" type="flex" align="middle">
                <el-col :span="8">右轴最大<el-tooltip content="可设置`dataMax`字样表示自动取最大值"><i class="el-icon-question"></i></el-tooltip></el-col>
                <el-col :span="16"><el-input clearable v-model="popupChartOption.yAxis[1].max" type="text" placeholder="右轴最大值" size="mini"></el-input></el-col>
              </el-row>
              <br>
              </span>
              <el-row :gutter="1" type="flex" align="middle">
                <el-col :span="8">文字水印</el-col>
                <el-col :span="16"><el-input clearable v-model.trim="chartWartermark" placeholder="文字,不填为无水印."></el-input></el-col>
              </el-row>
              <br>
              <el-row :gutter="1" type="flex" align="middle">
                <el-col :span="8">工具箱</el-col>
                <el-checkbox v-model="showChartToolBox" @change="popupChartOption.toolbox.show = showChartToolBox">显示</el-checkbox>
              </el-row>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-dialog>

    <!-- 提取数据显示弹窗 -->
    <el-dialog :visible.sync="showSheetDataViewer" :title="currentSheet.name" width="50%" top="2%">
      <el-table v-loading='sheetDataLoading' :data="extraDataList" height="70vh">
        <el-table-column prop="datadate" label="日期" width="100px"></el-table-column>
        <el-table-column show-overflow-tooltip v-for="item,index in extraDataHeaderList" :prop="item.prop" :label="item.name" :key="index" width="250px"></el-table-column>
      </el-table>
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :pager-count="5"
      :current-page="extraPage"
      :page-sizes="[150, 200, 300, 400]"
      :page-size="extraPageSize"
      layout="total, sizes, prev, pager, next, jumper"
      size='mini'
      :total="extraDataCache.length">
      </el-pagination>

    </el-dialog>

    <!-- 指标运算弹窗(生成新指标的公式) -->
    <el-dialog
      :visible.sync="showCalculateDialog"
      :close-on-click-modal="false"
      title="指标运算出新指标"
      width="70%"
    >
      <div style="padding:10px 15px;">
        <div>
          <span>指标命名：</span>
          <el-input v-model="calculateIndexObj.name" type="text" placeholder="输入运算结果的新指标名称" style="width: 734px;"></el-input>
        </div>
        <br>
        <div>
          <span>指标频率：</span>
          <el-select v-model="calculateIndexObj.frequency">
            <el-option value="日" label="日"></el-option>
            <el-option value="周" label="周"></el-option>
            <el-option value="月" label="月"></el-option>
            <el-option value="季" label="季"></el-option>
            <el-option value="年" label="年"></el-option>
          </el-select>
          <span style="margin-left: 10px;">指标单位：<el-input v-model.trim="calculateIndexObj.unit" style="width: 215px;" placeholder="输入新的指标单位"></el-input></span>
        </div>
        <br>
        <div style="display: flex;align-items: center;">
          <div>公式构建：</div>
          <el-select v-model="cacheSelectIndex" @change="makeCalculateFormula" style="margin-right: 10px;">
            <el-option v-for="item,index in multipleSelection" :label="item.name" :value="item.formula" :key="index"></el-option>
          </el-select>
          <el-button type="primary" @click="makeCalculateFormula('+')">加</el-button>
          <el-button type="primary" @click="makeCalculateFormula('-')">减</el-button>
          <el-button type="primary" @click="makeCalculateFormula('*')">乘</el-button>
          <el-button type="primary" @click="makeCalculateFormula('/')">除</el-button>
          <el-button type="primary" @click="makeCalculateFormula('(')">(</el-button>
          <el-button type="primary" @click="makeCalculateFormula(')')">)</el-button>
          <el-button type="primary" @click="addNumberToFormula(cacheNumber)">常数</el-button>
          <el-input v-model="cacheNumber" placeholder="在这里输入常数值" style="width: 140px;margin-left: 4px;"></el-input>
        </div>
        <br>
        <div>
          <div>公式预览：<span style="font-size: 11px;color: #F34D37;">程序没有对公式进行严格验证,请构建符合数学计算的表达式，乘号不要省略。</span></div>
          <div style="height: 36px;background-color:#ecf8ff;border-radius: 8px;position: relative;line-height: 36px;">
          <span style="padding: 0 10px;">{{ calculateIndexObj.formula }}</span>
          <span style="position: absolute;right: 5px;"><i class="el-icon-delete" style="cursor: pointer;color: #F34D37;" @click="clearCalculateFormula"></i></span>
          </div>
        </div>
      </div>
      <div slot='footer'>
        <el-button type="primary" :loading="saveCalculateLoading" @click="saveNewCalcaluteIndex">确定添加</el-button>
      </div>
    </el-dialog>

    <!-- 我的数据指标Drawer -->
    <el-drawer :visible.sync="myIndexData.isShow" :modal="false" size="50%">
      <template #title>
        <div class="draw-title">我的品种数据指标库</div>
        <div class="refresh" @click="toReloadMyIndex">
          <i class="el-icon-refresh"></i>
        </div>
      </template>
      <div class="draw-content">
        <div class="sheet-show">
          <span style="color: red">*</span>
          操作表：
          <el-select
            v-model="myIndexData.currentSheetId"
            size="mini"
            placeholder="请选择要往哪张表中添加指标"
            style="min-width: 350px"
            @change="drawerSheetChange"
          >
            <el-option
              v-for="s in sheetList"
              :key="s.id"
              :value="s.id"
              :label="s.name"
            />
          </el-select>
        </div>
        <el-tree
          ref="drawerTree"
          lazy
          node-key="id"
          :load="loadGroupOrIndexes"
          :props="{ label: 'name', isLeaf: 'leaf' }"
          :data="myIndexData.dataList"
        >
          <div slot-scope="{ node, data }" class="tree-node">
            <div v-if="data.is_index" class="index-node">
              <div @dblclick="toAddSheet(data)">
                <i class="el-icon-tickets"></i>
                {{ data.name }}
              </div>
              <div class="actions">
                <span class="info-span">{{ data.source_plat }}</span>
                <span class="info-span">{{ data.source_id }}</span>
                <i class="el-icon-sold-out" @click="toAddSheet(data)"></i>
                <i class="el-icon-close" @click="toRemoveIndex(data, node)"></i>
              </div>
            </div>
            <div v-else>
              {{ data.name }}
            </div>
          </div>
        </el-tree>
      </div>
    </el-drawer>
  </div>
</template>

<script>
  let NAME_SPACE = 'V03'  // 数据库
  import { baseURL } from '@/config'
  import VabChart from '@/plugins/echarts'
  import { datetimeToStr, getDateOfYear } from '@/utils/datetimeUtils'
  import { getEDBTables, getMyFormula } from '@/api/edbdata/datalib'
  import { getUserAuthVariety } from '@/api/operations/variety'
  import {
    createMySheet,
    delSheet,
    addSheetColumn,
    getSheetColumns,
    delSheetColumn,
    extraColumnsData,
    saveChartOption,
    getMyDatalibGroup,
    getMyGroupIndex,
    deleteMyGroupIndex
  } from '@/api/edbdata/personal'
  import { getVarietySheet } from '@/api/edbdata/variety'
  export default{
    components:{
      VabChart
    },
    data() {
      return {
        guidePdfUrl: baseURL + '/storagefile/AppFiles/guide/构建品种图表库.pdf',
        isShowOwn: true,
        varietyList: [],
        currentVariety: { variety_en: '' },
        newSheetName: '',
        loadingVarietySheet: false,
        sheetList: [],
        currentSheet: {},
        curSheetColumnList: [], // 当前数据指标列表

        showIndexForAdd: false,
        searchIndexLoading: false,
        searchSheetVariety: null,
        searchSheetWords: '', // 待搜索指标
        searchPage: 1,
        searchPageSize: 50,
        searchTotalCount: 0,
        querySheetList: [], // 搜索出待添加指标

        multipleSelection: [], // 数据表指标列选择结果
        exportExcelLoading: false,
        minTableHeight: '250',

        queryFormulaList: [], // 搜索出待添加的公式
        showFormulaTable: false,

        // 查看表数据弹窗
        showSheetDataViewer: false,
        sheetDataLoading: false,
        extraDataCache: [],
        extraDataHeaderList: [],
        extraPage: 1,
        extraPageSize: 150,
        extraDataList: [], // 将缓存数据显示到表格中

        // 制图弹窗参数
        isSeasonChart: false,
        chartDataLoading: false, // 数据可视化的loading
        chartDialogFullScreen: false,
        showMakeChartDialog: false,
        chartWartermark: '瑞达期货研究院',
        makeChartDataCache: {
          table_header: [],
          table_value: []
        },
        chartSeriesIndex:[],
        xAxisFormate: '%Y-%m-%d',
        xAxisStartDate: null,
        xAxisEndDate: null,
        showChartToolBox: false,
        showChartMaxLabel: null,
        saveChartLoading: false,
        cacheXaxisData: [], // 缓存横轴数据，在改变横轴格式时可使用
        cacheSeriesData: [], // 缓存图形数据，在横轴范围改变时可使用
        initChartOption: {
          title: { text: '', left: 'center' },
          grid: {
            top: '56',
            left: '12',
            right: '24',
            bottom: '21',
            containLabel: true,
          },
          toolbox: {
            show: false,
            feature: {
              dataZoom: {
                yAxisIndex: 'none'
              },
              dataView: { readOnly: false },
              saveAsImage: {}
              }
            },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: [
            {
              type: 'category',
              /*boundaryGap: false,*/
              data: [],
              axisTick: {
                alignWithLabel: true,
              },
              axisLabel: {
                rotate: 0,
                showMaxLabel:null
              }
            },
          ],
          yAxis: [
            {
              type: 'value',
              position: 'left',
              min: null,
              max: null
            },
            {
              show:false,
              type: 'value',
              position: 'right',
              min: null,
              max: null
            },
          ],
          series: [
            {
              name: '',
              type: 'line',
              symbol: 'none',
              data: [],
            },
          ],
          legend: {
            width: 500, // 跟容器的宽度一致
            bottom: 0,
            data: []
          }
        },
        popupChartOption: {},

        // 指标运算弹窗
        showCalculateDialog: false,
        saveCalculateLoading: false,
        cacheSelectIndex: '',
        cacheNumber: 0,
        calculateIndexObj: {
          name: '',
          formula: '',
          frequency: '日',
          unit: '',
        },

        // 我的数据指标
        myIndexData: {
          isShow: false,
          isLoaded: false,
          autoLoaded: false,
          clickGroup: 0,
          currentSheetName: '未选择',
          currentSheetId: null,
          dataList: [],
        },
      }
    },
    watch: {
      xAxisStartDate(n, o){
        this.xAxisDateRangeChange(n, 'start')
      },
      xAxisEndDate(n, o){
        this.xAxisDateRangeChange(n, 'end')
      },
    },
    created() {
      this.popupChartOption = JSON.parse(JSON.stringify(this.initChartOption))
      this.showChartMaxLabel = null
    },
    mounted() {
      this.getVariety()
    },
    methods: {
      // 显示我的数据指标
      toShowMyIndexes() {
        if (!this.currentVariety.variety_en) {
          this.$baseMessage('请先选择品种!', 'error')
          return
        }
        // 树形控件懒加载初始自己请求一次数据
        if (!this.myIndexData.isLoaded && this.myIndexData.autoLoaded) {
          this.queryMyDbGroup()
        }
        this.myIndexData.isShow = true
      },
      // 重新请求我的指标分组
      toReloadMyIndex() {
        this.queryMyDbGroup()
        this.$baseMessage('刷新成功!', 'success')
      },
      // 请求我的数据库指标组
      queryMyDbGroup() {
        getMyDatalibGroup(
          this.currentVariety.variety_en,
          this.myIndexData.clickGroup
        ).then((res) => {
          // console.log(res)
          const groups = res.data.data
          this.myIndexData.dataList = groups
          this.myIndexData.isLoaded = true
        })
      },
      // 请求组或者指标
      loadGroupOrIndexes(node, resolve) {
        // console.log('node', node)
        const nodeData = node.data
        getMyDatalibGroup(this.currentVariety.variety_en, nodeData.id).then(
          async (res) => {
            this.myIndexData.autoLoaded = true
            let resolveData = res.data.data
            if (resolveData.length === 0) {
              const res = await getMyGroupIndex(nodeData.id)
              resolveData = res.data.indexes
            }
            resolve(resolveData)
          }
        )
      },
      // 从我的指标库将指标加入表
      toAddSheet(item) {
        if (!this.currentSheet.id || this.currentSheet.id < 1) {
          this.$baseMessage('还没有选择操作表，若没有表请先新建！', 'error')
          return
        }
        this.addFormulaToSheet(item, -1)
      },
      // 将指标移出我的指标库
      toRemoveIndex(item, node) {
        console.log('确认移出', item)
        this.$baseConfirm(
          '指标将被移出该数据库分组，请谨慎操作！',
          '提示',
          () => {
            deleteMyGroupIndex(item.id).then((res) => {
              this.$refs.drawerTree.remove(node)
            })
          }
        )
      },

      removeGroupOneIndex(rowId) {
        const indexData = this.myIndexData.dataList
      },

      drawerSheetChange(sheetId) {
        this.currentSheet.id = sheetId
        for (let i = 0; i < this.sheetList.length; i++) {
          const sheet = this.sheetList[i]
          if (sheet.id === sheetId) {
            this.sheetRowClicked(sheet)
            break
          }
        }
      },

      // 删除当前设计好的指标运算公式
      clearCalculateFormula() {
        this.cacheSelectIndex = ''
        this.calculateIndexObj.formula = ''
      },

      // 组织当前计算公式
      makeCalculateFormula(val) {
        this.calculateIndexObj.formula += val
      },
      addNumberToFormula(val){
        let num = parseFloat(val);
        if (!num) {
          return
        }
        this.makeCalculateFormula(num)
      },

      // 保存计算后的新指标
      saveNewCalcaluteIndex(){
        const columnData = {
          name: this.calculateIndexObj.name,
          sheet_id: this.currentSheet.id,
          formula: this.calculateIndexObj.formula,
          frequency: this.calculateIndexObj.frequency,
          unit: this.calculateIndexObj.unit,
        }
        let valuePassed = true
        for (let k in columnData){
          if (k !== 'unit' && !columnData[k]){
            valuePassed = false
            break
          }
        }
        if (!valuePassed){
          this.$baseMessage('请填写完信息再提交!', 'error')
          return false
        }
        this.saveCalculateLoading = true
        addSheetColumn(columnData).then(res => {
          this.$baseMessage(res.msg, 'success')
          this.saveCalculateLoading = false
          this.showCalculateDialog = false  // 关闭计算弹窗
          this.refreshSheetColumns()  // 刷新当前表的指标数据
        }).catch(err => {
          this.saveCalculateLoading = false
        })
      },

      // 将表选中的列导出EXCEL
      exportExcelFile(){
        let filename = this.currentSheet.name
        this.exportExcelLoading = true
        extraColumnsData(this.multipleSelection, filename).then(res => {
          this.exportExcelLoading = false
          //1.先创建一个a标签
          let a = document.createElement("a");
          //2.给a标签的href赋上下载地址
          a.href = res.data.file_url;
          //3.让a标签不显示在视图中
          a.style.display = "none";
          //4.将a标签append到文档中
          document.body.appendChild(a);
          //5.a标签自点击
          a.click();
          //6.点击下载后，销毁这个节点
          document.body.removeChild(a);
        })
      },

      // 弹窗指标运算
      toShowIndexCalcultor(){
        this.cacheSelectIndex = ''
        this.cacheNumber = 0
        this.calculateIndexObj.name = ''
        this.calculateIndexObj.formula = ''
        this.calculateIndexObj.frequency = ''
        this.calculateIndexObj.unit = ''
        this.showCalculateDialog=true
      },

      // 查看表数据
      sheetDataViewer(){
        this.showSheetDataViewer = true
        this.sheetDataLoading = true
        extraColumnsData(this.multipleSelection).then(res => {
          const data = res.data
          this.extraDataCache = data.table_value
          this.extraDataHeaderList = data.table_header
          this.sheetDataLoading = false
          this.showExtraTable()
        })
      },
      // 将数据显示到表格中
      showExtraTable(){
        let startIndex = (this.extraPage - 1) * this.extraPageSize
        this.extraDataList = JSON.parse(JSON.stringify(this.extraDataCache.slice(startIndex, startIndex + this.extraPageSize)))
      },
      // 显示数据的表格页码变化
      handleSizeChange(size){
        this.extraPageSize = size
        this.extraPage = 1
        this.showExtraTable()
      },
      handleCurrentChange(page){
        this.extraPage = page
        this.showExtraTable()
      },

      // 删除表
      toDelSheet(sheetItem){
        this.$baseConfirm('你确定要删除这个表，删除不可恢复!', null, async () => {
          delSheet(sheetItem.id).then(res => {
            this.$baseMessage(res.msg, 'success')
            this.getSheetWithVariety()
            // 清空右侧的指标
            this.curSheetColumnList = []
            this.multipleSelection = []
          })
        })

      },

      // 点击表
      sheetRowClicked(item) {
        this.currentSheet = Object.assign(this.currentSheet, item)
        this.showIndexForAdd = false
        this.refreshSheetColumns()
        this.myIndexData.currentSheetId = item.id
      },

      // 刷新当前表下的指标列
      refreshSheetColumns() {
        getSheetColumns(this.currentSheet.id).then((res) => {
          this.curSheetColumnList = res.data
        })
      },

      // 表格指标列选择变化
      handleSelectionChange(val){
        this.multipleSelection = []
        for (let i=0;i<val.length;i++){
          this.multipleSelection.push({id: val[i].id, formula: val[i].formula, name: val[i].name})
        }
      },

      // 准备搜索指标来添加
      toSearchIndexes() {
        this.searchPage = 1
        if (this.showFormulaTable === true) {
          this.toSearchMyFormula()
        } else {
          this.searchRuizySheets()
        }
      },

      // 搜索指标的页码改变
      searchIndexPageChange(page) {
        this.searchPage = page
        if (this.showFormulaTable === true) {
          this.toSearchMyFormula()
        } else {
          this.searchRuizySheets()
        }
      },

      toSearchMyIndexes() {
        this.searchPage = 1
        this.searchRuizySheets()
      },

      // 搜索数据指标
      searchRuizySheets() {
        this.showFormulaTable = false
        const searchParams = {
          kw: this.searchSheetWords,
          v: this.searchSheetVariety,
          page: this.searchPage,
          page_size: this.searchPageSize,
        }
        this.searchIndexLoading = true
        getEDBTables(searchParams)
          .then((res) => {
            this.querySheetList = res.data.records
            this.searchPage = res.data.current_page
            this.searchTotalCount = res.data.total_count
            this.searchIndexLoading = false
          })
          .catch(() => {
            this.searchIndexLoading = false
          })
      },

      // 搜索我的公式
      toSearchMyFormula() {
        this.searchPage = 1
        this.showFormulaTable = true
        const searchParams = {
          kw: this.searchSheetWords,
          v: this.searchSheetVariety,
          page: this.searchPage,
          page_size: this.searchPageSize,
        }
        this.searchIndexLoading = true
        getMyFormula(searchParams)
          .then((res) => {
            console.log(res)
            this.queryFormulaList = res.data.data
            this.searchPage = res.data.page
            this.searchTotalCount = res.data.total_count
            this.searchIndexLoading = false
          })
          .catch(() => {
            this.searchIndexLoading = false
          })
      },

      // 将指标添加到表中
      addIndexToSheet(item, index) {
        const columnData = {
          name: item.name_zh,
          sheet_id: this.currentSheet.id,
          formula: `${item.source_plat}_${item.source_id}`,
          frequency: item.frequency,
          unit: item.unit
        }
        addSheetColumn(columnData).then((res) => {
          this.$baseMessage(res.msg, 'success')
          this.refreshSheetColumns() // 刷新当前表的指标数据
          this.querySheetList.splice(index, 1) // 去除待选里的指标对象
        })
      },

      // 将公式添加到表中
      addFormulaToSheet(item, index) {
        const columnData = {
          name: item.name,
          sheet_id: this.currentSheet.id,
          formula: item.formula,
          frequency: item.frequency,
          unit: item.unit,
        }
        addSheetColumn(columnData).then((res) => {
          this.$baseMessage(res.msg, 'success')
          this.refreshSheetColumns() // 刷新当前表的指标数据
          if (index > -1) {
            this.queryFormulaList.splice(index, 1) // 去除待选里的指标对象
          }
        })
      },

      // 添加环比计算指标
      toAddOnBasis(row) {
        const columnData = {
          name: row.name + '环比变化',
          sheet_id: row.sheet_id,
          formula: row.formula,
          frequency: row.frequency,
          unit: row.unit,
          is_diff: 1,
        }
        addSheetColumn(columnData).then(res => {
          this.$baseMessage(res.msg, 'success')
          this.refreshSheetColumns()  // 刷新当前表的指标数据
          this.querySheetList.splice(index, 1)  // 去除待选里的指标对象
        })
      },

      delIndexWithSheet(columnItem){
        this.$baseConfirm('你确定要删除指标吗', null, async () => {
          delSheetColumn(columnItem).then(res => {
            this.$baseMessage(res.msg, 'success')
            this.refreshSheetColumns()
          })
        })
      },

      // 新建表
      toCreateSheet(){
        if (!this.newSheetName){return}
        const sheetData = {name: this.newSheetName, variety_en: this.currentVariety.variety_en}
        createMySheet(sheetData).then(res => {
          this.$baseMessage(res.msg, 'success')
          this.newSheetName = ''
          this.getSheetWithVariety()
        })
      },

      // 只显示我选择改变
      isOwnChange(){
        this.getSheetWithVariety()
      },

      // 获取品种下的表
      getSheetWithVariety() {
        if (!this.currentVariety.variety_en) {
          return false
        }
        this.loadingVarietySheet = true
        const queryParams = {
          variety: this.currentVariety.variety_en,
          own: this.isShowOwn ? 1 : 0
        }
        getVarietySheet(queryParams).then(res => {
          this.sheetList = res.data.sort(this.sortList('sorted',false))
          this.loadingVarietySheet = false
        })
        // 设置我的数据库指标组获取状态为false
        this.myIndexData.isLoaded = false
      },

      // 获取品种
      getVariety(){
        getUserAuthVariety({space: NAME_SPACE}).then(res => {
          this.varietyList = res.data
        })
      },

      // 前往制作图形
      toMakeCharts(){
        this.isSeasonChart = false  // 还原为普通图形格式
        this.saveChartLoading = false  // 保存半年状态还原
        this.xAxisFormate = '%Y-%m-%d'  // 还原横轴格式
        // 先提取数据
        this.chartDataLoading = true
        extraColumnsData(this.multipleSelection).then(res => {
          this.makeChartDataCache.table_header = res.data.table_header
          this.makeChartDataCache.table_value = res.data.table_value
          // console.log(this.makeChartDataCache);
          // 生成左侧指标设置
          this.chartSeriesIndex = []
          for (let i=0;i<this.makeChartDataCache.table_header.length;i++){
            let item = this.makeChartDataCache.table_header[i]
            this.chartSeriesIndex.push({
              isChecked: false,
              name: item.name,
              prop: item.prop,
              unit: item.unit,
              formula: item.formula,
              yIndex: 0,
              chartType: 'line',
              noZero: true, // 数据是否含0绘制
              is_diff: item.is_diff?true:false  // 否则无法计算
            })
          }
          this.popupChartOption = JSON.parse(JSON.stringify(this.initChartOption))  // 初始化弹窗图形的参数
          this.showMakeChartDialog = true
          this.showChartMaxLabel = null
          this.chartDataLoading = false
          // this.drawTargetChartUp()  // 手动初次绘制图形
        }).catch(() => {
          this.chartDataLoading = false
        })
      },

      // 图形横轴显示最大刻度改变
      chartMaxLabelShowChange(){
        let chartOpt = JSON.parse(JSON.stringify(this.popupChartOption))
        if (!this.showChartMaxLabel){
          chartOpt.xAxis[0].axisLabel.showMaxLabel = null
        }else{
          chartOpt.xAxis[0].axisLabel.showMaxLabel = true
        }
        console.log(this.popupChartOption);
        this.popupChartOption = chartOpt
      },

      // 图形横轴格式改变
      xAxisFomateChange(f){
        if(this.isSeasonChart){
          this.$baseMessage('季节图形不支持调整横轴格式', 'info')
          return false
        }  // 季节图形不改变任何配置
        let len = 10
        if (f === '%Y-%m'){len = 7}
        if (f === '%Y'){len = 4}
        if (this.xAxisStartDate!==null || this.xAxisEndDate !== null){
          this.xAxisStartDate = null
          this.xAxisEndDate = null
        } else {
          // 从缓存的xData进行数据处理
          const xAxisData = this.cacheXaxisData.map(item => item.slice(0,len))
          this.popupChartOption.xAxis[0].data = xAxisData
          this.popupChartOption.series = this.cacheSeriesData
        }

      },

      // 在缓存数据中找到位置下标
      getDataIndexInCacheData(dateStr){
        let len = 10
        if (this.xAxisFormate === '%Y-%m'){len = 7}
        if (this.xAxisEndDate === '%Y'){len = 4}
        let findDate = dateStr.slice(0,len)
        let findIndex = -1
        for (let i=0;i<this.cacheXaxisData.length;i++){
          if (this.cacheXaxisData[i]>=findDate){
            findIndex = i
            break
          }
        }
        return findIndex
      },

      // 图形横轴日期范围改变
      xAxisDateRangeChange(oDate, endpoint){
        if (this.isSeasonChart){ //  季节图形时，直接重画
          this.drawTargetChartUp()
          return false
        }
        // 非季节图形，改变即可（可优化：非季节图形也可以直接重画）
        let startIndex = 0
        let endIndex = undefined
        if (this.xAxisStartDate !== null){
          startIndex = this.getDataIndexInCacheData(datetimeToStr(this.xAxisStartDate,true,'-'))
        }
        if (this.xAxisEndDate !== null){
          endIndex = this.getDataIndexInCacheData(datetimeToStr(this.xAxisEndDate,true,'-'))
        }
        let seriesData = []
        for (let i=0;i<this.cacheSeriesData.length;i++){
          let sObj = JSON.parse(JSON.stringify(this.cacheSeriesData[i]))
          sObj.data = sObj.data.slice(startIndex, endIndex)
          seriesData.push(sObj)
        }
        // 设置x轴
        let xAxisData = JSON.parse(JSON.stringify(this.cacheXaxisData)).slice(startIndex, endIndex)
        let len = 10
        if (this.xAxisFormate === '%Y-%m'){len = 7}
        if (this.xAxisFormate === '%Y'){len = 4}
        this.popupChartOption.xAxis[0].data = xAxisData.map(item => item.slice(0,len))
        // 设置图形
        this.popupChartOption.series = seriesData  // 修改具体图形
      },

      // 制作图形弹窗关闭,清空释放数据缓存
      makeChartDialogClosed(){
        this.makeChartDataCache.table_header = []
        this.makeChartDataCache.table_value = []
      },

      // 将制作图形的缓存数据准变为以年份分开的各数据段(季节图形使用)
      handleChartDataCache(valueKey){
        let yearList = []
        let cacheData = {}
        let seriesData = {}
        let xAxisData = getDateOfYear()

        for (let i=0;i<this.makeChartDataCache.table_value.length;i++){
          let valueItem = this.makeChartDataCache.table_value[i]
          let datayear = valueItem.datadate.slice(0,4)
          // 循环中去除数据区间
          if (this.xAxisStartDate && datetimeToStr(this.xAxisStartDate, true, '-')>=valueItem.datadate){
            continue
          }
          if (this.xAxisEndDate && datetimeToStr(this.xAxisEndDate, true, '-') <= valueItem.datadate){
            continue
          }
          if (yearList.indexOf(datayear) === -1){
            yearList.push(datayear)
            seriesData[datayear] = []
          }
          seriesData[datayear].push(valueItem)
        }
        for (let y in seriesData){
          let yData = seriesData[y]
          seriesData[y] = xAxisData.map(day => {
            for (let j=0;j<yData.length;j++){
              if(yData[j].datadate.slice(5) === day){
                return yData[j][valueKey]
              }
            }
          })
        }
        return [xAxisData, seriesData]
      },

      // 图形类别发生变化，普通图形变为季节图形
      drawTargetChartUp(){
        const echartObject = this.$refs.popChart
        if (echartObject){
          echartObject.clear()  // 清空原来的图形
        }else{
          return false
        }

        if (this.isSeasonChart){ // 显示季节图形
          this.drawSeasonChart()
        }else{  // 显示普通图形
          this.drawNormalChart()
        }
      },

      // 绘制季节图形
      drawSeasonChart(){
        let chartOption = JSON.parse(JSON.stringify(this.popupChartOption))  // 重新使用option对象，才会使用notMerge: true
        let xAxisData = []
        let yAxis = [{type: 'value', position: 'left', name: null, min:null, max: null},
        {type: 'value', position: 'right', name: null, min: null, max: null, show:false, splitLine: {show: false}},]
        let seriesList = []
        let legendData = []
        for (let i=0;i<this.chartSeriesIndex.length;i++){
          let indexObj = this.chartSeriesIndex[i]
          if (indexObj.isChecked){
            yAxis[0].name = indexObj.unit
            // 获取根据年份处理后的数据
            let handleData = this.handleChartDataCache(indexObj.prop)
            xAxisData = handleData[0]
            for (let ky in handleData[1]){
              let dataList = handleData[1][ky]
              if (indexObj.noZero){
                dataList = dataList.map(i => i === 0?'':i)  // 去数据0
              }
              seriesList.push({
                symbol: 'none',
                 connectNulls: true,
                 name: ky,
                 type: 'line',
                 yAxisIndex:0,
                 data: dataList,
              })

              legendData.push(ky)
            }
            break  // 只允许使用一个指标绘制季节地图
          }
        }
        chartOption.xAxis[0].data = xAxisData  // 设置x轴数据
        chartOption.yAxis = yAxis  // 设置y轴
        chartOption.series = seriesList  // 添加具体图形
        chartOption.legend.data = legendData  // 图例
        this.popupChartOption = chartOption  // 将option设置给chart,调用echarts.setOption(option,true) 第二个参数为true是因为次数为新的Option对象

      },

      // 绘制普通图形
      drawNormalChart(){
        let chartOption = JSON.parse(JSON.stringify(this.popupChartOption))  // 重新使用option对象，才会使用notMerge: true
        // 将变化后的指标参数绘制图形
        let xAxisInitail = false  // 是否初始化x轴数据
        let xAxisData = []  // x轴坐标数据
        let yAxis = [
          {type: 'value', position: 'left', name: null, min: null, max: null},
          {type: 'value', position: 'right', name: null, min: null, max: null, show:false, splitLine: {show: false}},
        ]  // y轴数据
        let seriesList = []  // 图形容器
        let legendData = []  // 图例数据

        for (let i=0;i<this.chartSeriesIndex.length;i++){
          let indexObj = this.chartSeriesIndex[i]
          if (indexObj.isChecked){
            if (indexObj.yIndex === 0){yAxis[0].name = indexObj.unit}
            if (indexObj.yIndex === 1){
              yAxis[1].name = indexObj.unit
              yAxis[1].show = true
              // yAxis.push({type: 'value', position: 'right', name: indexObj.unit, min: null, max: null })
              }  // 添加右轴

            // 根据indexObj的prop循环table_value,做出图形的数据对象
            let oSeries = {
              symbol: 'none',
              connectNulls: true,
              name: indexObj.name,
              type: indexObj.chartType,
              yAxisIndex:indexObj.yIndex,
              data: [],
            }  // 具体图形数据对象
            for (let j=0;j<this.makeChartDataCache.table_value.length;j++){
              let valueItem = this.makeChartDataCache.table_value[j]
              if (!xAxisInitail){xAxisData.push(valueItem.datadate)}
              if (indexObj.noZero){
                oSeries.data.push(valueItem[indexObj.prop]===0?'':valueItem[indexObj.prop])
              }else{
                oSeries.data.push(valueItem[indexObj.prop])
              }
            }
            // 添加图例
            legendData.push({name: indexObj.name})
            xAxisInitail = true
            seriesList.push(oSeries)
          }
        }
        chartOption.xAxis[0].data = xAxisData  // 设置x轴数据
        chartOption.yAxis = yAxis  // 设置y轴
        chartOption.series = seriesList  // 添加具体图形
        chartOption.legend.data = legendData  // 图例
        // chartOption.legend.width = echartObject.getWidth()  // 图例宽度固定保证图例自动换行,不动态设置，不然无法确定横轴距离
        this.popupChartOption = chartOption  // 将option设置给chart,调用echarts.setOption(option,true) 第二个参数为true是因为次数为新的Option对象
        // 将横轴数据缓存供改变格式时使用
        this.cacheXaxisData = JSON.parse(JSON.stringify(xAxisData))
        // 将序列数据缓存供横轴时间改变时使用
        this.cacheSeriesData = JSON.parse(JSON.stringify(seriesList))
      },

      // 保存图形的配置
      confirmSaveChartOption(){
        // console.log(this.popupChartOption);
        // console.log(this.chartSeriesIndex);
        if (!this.popupChartOption.title.text){
          this.$baseMessage('请设置图形名称后再保存!', 'error')
          return false
        }
        // 复制数据
        let rawChartOption = JSON.parse(JSON.stringify(this.popupChartOption))
        let seriesOption = JSON.parse(JSON.stringify(this.chartSeriesIndex))
        if (rawChartOption.series.length<1){
          this.$baseMessage('请选择指标可视化后再保存图形!', 'error')
          return false
        }
        // 删除掉配置里的具体数据，减少网络消耗
        rawChartOption.xAxis[0].data = []
        rawChartOption.legend.data = []
        rawChartOption.series = []
        const chartOptionData = {
          chart_type: this.isSeasonChart?'season':'common',
          name: rawChartOption.title.text,
          sheet_id: this.currentSheet.id,
          variety: this.currentVariety.variety_en,
          options: rawChartOption,
          indication: seriesOption,
          is_open: 1,
          watermark: this.chartWartermark,
          xaxis_format: this.xAxisFormate,
          startdate: datetimeToStr(this.xAxisStartDate, true, '-'),
          enddate: datetimeToStr(this.xAxisEndDate, true, '-')
        }
        this.saveChartLoading = true
        saveChartOption(chartOptionData).then(res => {
          this.$baseMessage('保存图形成功!', 'success')
          this.saveChartLoading = false
          this.popupChartOption = JSON.parse(JSON.stringify(this.initChartOption))  // 初始化弹窗图形的参数
          this.showChartMaxLabel = null
        }).catch(()=> {
          this.$baseMessage('保存图形失败了!', 'error')
          this.saveChartLoading = false
        })
      },

      // 排序数据方法
      sortList(key, asc) {
        if (asc) {
          return (a, b)=> a[key]>=b[key]?1:-1
        }else{
          return (a, b)=> a[key]>=b[key]?-1:1
        }
      }
    }
  }
</script>

<style scoped lang="scss">
  .el-icon-full-screen,
  .el-icon-close,
  .el-icon-crop,
  .el-icon-refresh {
    cursor: pointer;
  }
  .el-icon-full-screen:hover,.el-icon-crop:hover{color: #1386D2;}
  .el-icon-close:hover{color: #F34D37;}
  .el-pagination{text-align: left;}
  .flex-item{margin-right: 5px;}
  .chart-dialog .el-dialog__header{padding: 5px 20px !important;}
  .el-card ::v-deep .el-card__body{padding: 0px;}
  .right-header{background-color: #FAC858;padding: 0px 8px;height: 32px;vertical-align: middle;}
  .header-action{
    cursor: pointer;
    text-decoration: underline;
    color: #666;
    margin-right: 12px;
  }
  .header-action:hover{color: #1890FF;}

  .show-btns{opacity: 1;}
  .list-action-btns{
      // margin-left: auto;
      opacity: 0;
      transition: opacity .1s;
      position: absolute;
      right: 0;
      .el-button{
          transform: scale(0.7);// 缩小按钮
          & + .el-button{
              margin-left: -1px;
          }
      }
  }
  .shee-name-node{
    position: relative;
    height: 32px;
    line-height: 32px;
    padding-left: 12px;
    border-bottom: 1px solid #f6f6f6;
    &:hover{
      background-color: #f6f6f6;
      .list-action-btns{
        @extend .show-btns;
      }
    }
  }
  .sheet-name{
    &:hover{
      color: #1386D2;
      cursor: pointer;
    }
  }
  .table-index-name {
    cursor: default;
    &:hover {
      color: #f34d37;
    }
  }
  .draw-title {
    border-bottom: 1px solid #888;
    margin-bottom: -32px;
    line-height: 30px;
  }
  .refresh {
    margin-left: auto;
    margin-right: 25px;
    margin-bottom: -32px;
  }
  .draw-content {
    .sheet-show {
      margin-left: 20px;
      margin-bottom: 10px;
    }
    .tree-node {
      width: 100%;
      margin-right: 15px;
    }
    .index-node {
      display: flex;
      align-items: center;
      color: #000;
      background-color: #f5f7fa;
      padding: 2px 10px;
      height: 26px;
      &:hover {
        background-color: #d5dfee;
        .info-span {
          opacity: 1;
        }
      }
      .info-span {
        margin: 0 20px;
        color: #a9a9a9;
        opacity: 0;
      }
      .actions {
        margin-left: auto;
        .el-icon-sold-out {
          color: #1890ff;
          margin-right: 10px;
          font-size: 18px;
        }
        .el-icon-close {
          color: #e40000;
        }
      }
    }
  }
</style>
